package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import server.core.Connector;
import server.core.Host;
import server.core.Mapper;
import server.core.WebappsClassLoader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.*;

/**
 * Maggie
 */
public class Bootstrap {

  // socket监听端口
  private int port = 8080;

  private Map<String, HttpServlet> servletMap = new HashMap<>();

  public int getPort() {
    return port;
  }

  public void setPort(int port) {
    this.port = port;
  }

  public void start() {
    Mapper mapper = init();

    int corePoolSize = 10;
    int maximumPoolSize = 50;
    long keepAliveTime = 100;
    TimeUnit unit = TimeUnit.SECONDS;
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
    ThreadFactory threadFactory = Executors.defaultThreadFactory();
    RejectedExecutionHandler handle = new ThreadPoolExecutor.AbortPolicy();
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handle);
    try {
      int port = mapper.getConnector().getPort();
      ServerSocket serverSocket = new ServerSocket(port);
      System.out.println("=====>>Minicat start on port: " + port);
      while (true) {
        Socket socket = null;
        try {
          socket = serverSocket.accept();RequestProcessor requestProcessor = new RequestProcessor(socket, mapper.getMappedContextMap());
          threadPoolExecutor.execute(requestProcessor);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private Mapper init() {
    // 解析server.xml
    Mapper mapper = new Mapper();

    InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
    SAXReader saxReader = new SAXReader();
    try {
      Document document = saxReader.read(resourceAsStream);
      Element rootElement = document.getRootElement();
      Element connectorEle = ((Element) rootElement.selectSingleNode("//Connector"));
      String port = connectorEle.attributeValue("port");
      Element hostEle = ((Element) rootElement.selectSingleNode("//Host"));
      String name = hostEle.attributeValue("name");
      String appBase = hostEle.attributeValue("appBase");
      Connector connector = new Connector();
      connector.setPort(Integer.parseInt(port));
      mapper.setConnector(connector);
      mapper.setHost(new Host(name, appBase));
      // 遍历appBase
      File dir = new File(appBase);
      File[] files = dir.listFiles();
      for (File file : files) {
        if (file.isDirectory()) {
          String contextPath = file.getName();
          String appPath = appBase + File.separatorChar + contextPath;
          File[] webXmlFile = file.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
              return "web.xml".equals(name);
            }
          });
          Map<String, HttpServlet> httpServletMap = loadServlet(new FileInputStream(webXmlFile[0]), appPath);
          List<Wrapper> wrappers = new ArrayList<>(10);
          httpServletMap.forEach((key, value) -> {
            Wrapper wrapper = new Wrapper();
            wrapper.setServlet(value);
            wrappers.add(wrapper);
          });
          Map<String, List<Wrapper>> mappedContextMap = mapper.getMappedContextMap();
          mappedContextMap.put(contextPath, wrappers);
        }
      }
    } catch (DocumentException | FileNotFoundException e) {
      e.printStackTrace();
    }
    return mapper;
  }

  private Map<String, HttpServlet> loadServlet(InputStream resourceAsStream, String appPath) {
      WebappsClassLoader webappsClassLoader = new WebappsClassLoader(appPath);
      Map<String, HttpServlet> servletMap = new HashMap<>();
      SAXReader saxReader = new SAXReader();
      try {
          Document document = saxReader.read(resourceAsStream);
          Element rootElement = document.getRootElement();
          List<Element> selectNodes = rootElement.selectNodes("//servlet");
          for (Element selectNode : selectNodes) {
              Element element = selectNode;
              Element servletNameElement = (Element) element.selectSingleNode("servlet-name");
              String servletName = servletNameElement.getStringValue();
              Element servletClassElement = (Element) element.selectSingleNode("servlet-class");
              String servletClass = servletClassElement.getStringValue();

              // /web-app/servlet-mapping[servlet-name=']?']
              String s = "/web-app/servlet-mapping[servlet-name='" + servletName + "']";
              // 根据servlet-name的值找到url-pattern
              Node servletMapping = rootElement.selectSingleNode(s);
              String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
              Object ins = webappsClassLoader.loadClass(servletClass).newInstance();
              servletMap.put(urlPattern, (HttpServlet) ins);
          }

      } catch (DocumentException | ClassNotFoundException e) {
          e.printStackTrace();
      } catch (IllegalAccessException e) {
          e.printStackTrace();
      } catch (InstantiationException e) {
          e.printStackTrace();
      }
      return servletMap;
  }

  public static void main(String[] args) {

    new Bootstrap().start();

  }
}
